package com.gitee.l0km.xthrift.base;

import java.util.ServiceLoader;
import static com.google.common.base.Preconditions.checkState;

/**
 * @author guyadong
 * @since 2.3.0
 */
public class ConnectionTest {
	private static class Singleton {
		private static final IConnectionTester INSTANCE = loadInstance();
		/**
		 * SPI方式加载{@link IConnectionTester}实例<br>
		 * 优先调用{@link ServiceLoader#load(Class)},如果返回为空则调用{@link ServiceLoader#load(Class, ClassLoader)}
		 */
		private static IConnectionTester loadInstance(){
			ServiceLoader<IConnectionTester> loader = ServiceLoader.load(IConnectionTester.class);
			if(!loader.iterator().hasNext()) {
				loader = ServiceLoader.load(IConnectionTester.class,IConnectionTester.class.getClassLoader());
			}
			checkState(loader.iterator().hasNext(),"NOT FOUND instance of %s",IConnectionTester.class.getName());
			return loader.iterator().next();
		}
	}
	/**
	 * 测试thrift服务连接<br>
	 * {@code timeoutMills}>0时设置连接超时参数
	 * @param host 主机名
	 * @param port 端口号
	 * @param timeoutMills 指定连接超时(毫秒),<=0使用默认值
	 * @return 连接成功返回{@code true},否则返回{@code false}
	 */
	public static final boolean testConnect(String host,int port,long timeoutMills){
		return Singleton.INSTANCE.testConnect(host, port, timeoutMills);
	}
}
